using AutoMapper;
using Finance.Api.Write.Applications.Commands.库存调拨;
using Finance.Domain.调拨;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;

namespace Finance.Api.Write.Applications.CommandHands.库存调拨
{
    public class DeploymentBatchDeleteCommandHandler : IRequestHandler<DeploymentBatchDeleteCommand, ApiResult<int>>
    {
        private readonly SqlsugarDb<DeploymentModel> db;
        private readonly IMapper mapper;

        public DeploymentBatchDeleteCommandHandler(SqlsugarDb<DeploymentModel> db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(DeploymentBatchDeleteCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    result.message = "请选择要删除的数据";
                    result.Code = Enumcode.fail;
                    return result;
                }

                var entities = await db.FirstQuery().Where(x => request.Ids.Contains(x.Id)).ToListAsync();
                if (entities.Count == 0)
                {
                    result.message = "查无数据";
                    result.Code = Enumcode.fail;
                    return result;
                }

                var successCount = 0;
                foreach (var entity in entities)
                {
                    // 直接更新实体，不使用AutoMapper
                    entity.IsDelete = true;
                    entity.DeleteTime = DateTime.Now;
                    entity.DeleteName = "管理员";
                    entity.LoginId = 1;

                    var res = await db.Updata(entity);
                    if (res > 0)
                    {
                        successCount++;
                    }
                }

                if (successCount == entities.Count)
                {
                    result.message = $"成功删除 {successCount} 条数据";
                    result.data = successCount;
                    result.Code = Enumcode.ok;
                }
                else
                {
                    result.message = $"成功删除 {successCount} 条数据，{entities.Count - successCount} 条删除失败";
                    result.data = successCount;
                    result.Code = Enumcode.fail;
                }
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.data = 0;
                result.Code = Enumcode.fail;
            }
            return await Task.FromResult(result);
        }
    }
} 